#任务模板，包含多个标准养护任务
class TemplateController < ApplicationController
  before_filter :sys_before_log

  #获取所有的标准模板信息
  def getTemplates
    forCBB = params[:for_cbb]
    if forCBB.nil?
      total = Template.count
      templates = Template.all
    else
      templates = Template.where("is_locked = ?",forCBB)
      total = templates.length
    end
    
    jsonStr="{template:"+templates.to_json()+",total:"+total.to_s+"}"
    render :text => jsonStr,:layout => false
  end

  def create
    begin
      template = Template.find_by_name params[:name]
      if template != nil
        info = '模板已存在，请更换！'
      else
        template = Template.new
        template.name = params[:name]
        template.sub_type = params[:taskType]
        template.save!
        info = 'success'
      end
    rescue Exception => e
      logger.info e
      info = '创建异常'
    end

    result = "{success:true,info:\"#{info}\"}"
    render :text => result,:layout => false
  end

  #锁定或解锁，只允许锁定。
  def doLock
    ids= params[:id][1..params[:id].length-2].split(',')
    for id in ids
      template = Template.find(id)
      if template.is_locked == 1
        template.is_locked = 0
      else
        template.is_locked = 1
      end
      template.save!
    end
    info = "success"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #获取指定模板的信息
  def edit
    template = Template.find(params[:id])
    jsonStr = template.to_json()
    render :text=>jsonStr,:layout=>false
  end

  def update
    begin
      template = Template.find(params[:id])
      if template.name == params[:name].to_s                                    #没改名字，直接改其他项
        template.sub_type = params[:taskType]
        template.save!
        info = 'success'
      else                                                                      #名字改了，找找有没有重名的
        templateUser = Template.find_by_name params[:name]
        if templateUser == nil
          template.name = params[:name]
          template.sub_type = params[:taskType]
          template.save!
          info = 'success'
        else
          info = '该模板已存在，请更换！'
        end
      end
    rescue Exception=>e
      logger.info e
      info = '更新异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end
end
